//
//  XMImageContainerView.m
//  XiaoMiao
//
//  Created by 23 on 2018/2/5.
//  Copyright © 2018年 smallyou. All rights reserved.
//

#import "XMImageContainerView.h"
#import "XMMaskPaintView.h"
#import "XMAlbumScrollView.h"

typedef NS_ENUM(NSInteger, XMJigsawStyle) {
    XMJigsawStyleTwo                    = 1,
    XMJigsawStyleFour                   = 2,
    XMJigsawStyleSix                    = 3,
    XMJigsawStyleTen                    = 4,
    XMJigsawStyleTwelve                 = 5,
    
};

@interface XMImageContainerView ()

/**拼图内容*/
@property(nonatomic,weak) UIView *jigsawView;

/**当前选中的样式按钮*/
@property(nonatomic,strong) UIButton *selectedStyleButton;
/**当前选中的样式*/
@property(nonatomic,assign) XMJigsawStyle currentStyle;

#pragma mark - 马赛克状态下的属性
/**马赛克绘制视图*/
@property(nonatomic,weak) XMMaskPaintView *maskPaintView;

@end


@implementation XMImageContainerView

- (instancetype)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        [self setupUI];
        
    }
    return self;
}

- (void)setupUI
{
    self.backgroundColor = kClearColor;
    
    UIView *jigsawView = [[UIView alloc] init];
    jigsawView.backgroundColor = [UIColor whiteColor];
    [self addSubview:jigsawView];
    self.jigsawView = jigsawView;
    
    UIImageView * logoImageView = [[UIImageView alloc]init];
    [logoImageView setImage:kImage(@"hslgoo")];
    [self.jigsawView addSubview:logoImageView];
    
    [logoImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.jigsawView).offset(15);
        make.left.equalTo(self.jigsawView).offset(15);
        make.width.equalTo(@90);
        make.height.equalTo(@20);
    }];
    
    UILabel * subTitleLabel = [[UILabel alloc]init];
    subTitleLabel.text = @"记 录 真 实 手 术 案 例";
    subTitleLabel.font = kFont(15);
    subTitleLabel.textColor = HEX_RGB(0xd8d6d5);
    [self.jigsawView addSubview:subTitleLabel];
    
    [subTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.jigsawView).offset(-20);
        make.bottom.equalTo(self.jigsawView).offset(-15);
    }];
    
    
}


- (void)setImagesArray:(NSArray *)imagesArray
{
    _imagesArray = imagesArray;
    
    
    //设置默认样式
    
    if (self.imagesArray.count >= 12) {
        self.currentStyle = XMJigsawStyleTwelve;
        
    }else if (self.imagesArray.count >= 10) {
        self.currentStyle = XMJigsawStyleTen;
    }else if (self.imagesArray.count >= 6) {
        self.currentStyle = XMJigsawStyleSix;
    }else if (self.imagesArray.count >= 4){
        self.currentStyle = XMJigsawStyleFour;
    }else if (self.imagesArray.count >= 2){
        self.currentStyle = XMJigsawStyleTwo;
    }
    
    //根据样式更新
    [self updateUIWithJigsawStyle:self.currentStyle];
    
}

/**根据样式更新视图*/
- (void)updateUIWithJigsawStyle:(XMJigsawStyle )jigsawStyle
{
    //移除
    for (UIView *view in self.jigsawView.subviews) {
        if ([view isKindOfClass:[XMAlbumScrollView class]]) {
            [view removeFromSuperview];
        }
    }
    
    UIView * contentView = [[UIView alloc]init];
    contentView.backgroundColor = kClearColor;
    [self.jigsawView addSubview:contentView];
    
    CGFloat LRMargin = 0;
    CGFloat marginW = 0;
    int oneRowNumber = 0;
    UIView  * lastImageView;
    switch (jigsawStyle) {
        case XMJigsawStyleTwo:
        {

            [self.jigsawView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.equalTo(self);
                make.height.equalTo(self.jigsawView.mas_width).multipliedBy(0.78);
                make.centerY.equalTo(self);
            }];
            

            
            //标准图
            XMAlbumScrollView *left = [[XMAlbumScrollView alloc] init];
            left.backgroundColor = HEX_RGB(0xbee5e4);
            XMAlbumScanModel *leftModel = [[XMAlbumScanModel alloc] init];
            leftModel.image = self.imagesArray[0];
            left.imageModel = leftModel;
            left.isScanner = YES;
            left.showsHorizontalScrollIndicator = NO;
            left.showsVerticalScrollIndicator = NO;
            [contentView addSubview:left];
            
            //标准图
            XMAlbumScrollView *right = [[XMAlbumScrollView alloc] init];
            right.backgroundColor = HEX_RGB(0xe0e0e0);
            XMAlbumScanModel *rightModel = [[XMAlbumScanModel alloc] init];
            rightModel.image = self.imagesArray[1];
            right.imageModel = rightModel;
            right.isScanner = YES;
            right.showsHorizontalScrollIndicator = NO;
            right.showsVerticalScrollIndicator = NO;
            [contentView addSubview:right];
            
            LRMargin = 10.f;
            marginW = 10.f;
            CGFloat imageWH = (kScreenWidth-2*LRMargin-marginW)/2;
            
            [left mas_makeConstraints:^(MASConstraintMaker *make) {
                
                make.left.equalTo(contentView).offset(marginW);
                make.centerY.equalTo(contentView);
                make.width.height.mas_equalTo(imageWH);
                
            }];

            [right mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.equalTo(contentView).offset(-marginW);
                make.centerY.equalTo(contentView);
                make.width.height.mas_equalTo(imageWH);
                
            }];
            
            [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(self.jigsawView);
                make.width.mas_equalTo(kScreenWidth);
                make.height.equalTo(right);
            }];
            
        }
            break;
        case XMJigsawStyleFour:
        {
            [self.jigsawView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.equalTo(self);
                make.height.equalTo(self.jigsawView.mas_width);
                make.centerY.equalTo(self);
            }];
            
            LRMargin = 42;
            marginW = 8;
            oneRowNumber = 2;
        }
            break;
        case XMJigsawStyleSix:
        {
            
            [self.jigsawView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.equalTo(self);
                make.height.equalTo(self.jigsawView.mas_width).multipliedBy(0.87);
                make.centerY.equalTo(self);
            }];
            
            LRMargin = 17;
            marginW = 5;
            oneRowNumber = 3;
        }
            break;
        case XMJigsawStyleTen:
        {
            [self.jigsawView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.equalTo(self);
                make.height.equalTo(self.jigsawView.mas_width).multipliedBy(0.648);
                make.centerY.equalTo(self);
            }];
            LRMargin = 14;
            marginW = 3;
            oneRowNumber = 5;
        }
            break;
        case XMJigsawStyleTwelve:
        {
            [self.jigsawView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.right.left.equalTo(self);
                make.height.equalTo(self.jigsawView.mas_width).multipliedBy(0.653);
                make.centerY.equalTo(self);
            }];
            
            LRMargin = 8;
            marginW = 3;
            oneRowNumber = 6;
        }
            break;

        default:
            break;
    }
    
    if (jigsawStyle != XMJigsawStyleTwo) {
        
        for (int i = 0; i < self.imagesArray.count; i++) {
            //标准图
            XMAlbumScrollView *imageView = [[XMAlbumScrollView alloc] init];
            imageView.backgroundColor = HEX_RGB(0xe0e0e0);
            XMAlbumScanModel *model = [[XMAlbumScanModel alloc] init];
            model.image = self.imagesArray[i];
            imageView.imageModel = model;
            imageView.isScanner = YES;
            imageView.showsHorizontalScrollIndicator = NO;
            imageView.showsVerticalScrollIndicator = NO;
            [contentView addSubview:imageView];
            
#warning 拖动事件 
//            UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizer:)];
//            [imageView addGestureRecognizer:pan];
            
            CGFloat imageWH = (kScreenWidth-(oneRowNumber-1)*marginW-LRMargin*2)/oneRowNumber;
            
            if (i%oneRowNumber) {
                [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                    
                    make.left.equalTo(lastImageView.mas_right).offset(marginW);
                    make.top.equalTo(lastImageView);
                    make.width.height.mas_equalTo(imageWH);
                    
                }];
                lastImageView = imageView;
            }else{
                
                if ( lastImageView == nil) {
                    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                        
                        make.left.equalTo(contentView).offset(LRMargin);
                        make.top.equalTo(contentView).offset(marginW);
                        make.width.height.mas_equalTo(imageWH);
                        
                    }];
                }else{
                    
                    [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
                        
                        make.left.equalTo(contentView).offset(LRMargin);
                        make.top.equalTo(lastImageView.mas_bottom).offset(marginW);
                        make.width.height.mas_equalTo(imageWH);
                        
                    }];
                }
                

                
                lastImageView = imageView;
                
            }
            
            [contentView layoutIfNeeded];
            [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.center.equalTo(self.jigsawView);
                make.width.mas_equalTo(kScreenWidth);

            make.height.mas_equalTo(lastImageView.height*2+2*marginW);
            }];
        }
    }
}


//- (void)panGestureRecognizer:(UIPanGestureRecognizer *)panGestureRecognizer{
//
//    if (panGestureRecognizer.state == UIGestureRecognizerStateEnded || panGestureRecognizer.state == UIGestureRecognizerStateCancelled) {
//        panGestureRecognizer.view.transform =CGAffineTransformMakeTranslation(0,0);
//    }else{
//        //获取拖拽手势在self.view 的拖拽姿态
//        CGPoint translation = [panGestureRecognizer translationInView:self];
//
//        panGestureRecognizer.view.transform = CGAffineTransformMakeTranslation(translation.x, translation.y);
//
////        for (<#type *object#> in <#collection#>) {
////            <#statements#>
////        }
//
//    }
//
//}

#pragma mark - action

#pragma mark - 工具方法
#define kBitsPerComponent (8)
#define kBitsPerPixel (32)
#define kPixelChannelCount (4)
/**对原图进行马赛克*/
- (UIImage *)maskWithImage:(UIImage*)orginImage blockLevel:(NSUInteger)level
{
    //获取BitmapData
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    CGImageRef imgRef = orginImage.CGImage;
    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);
    CGContextRef context = CGBitmapContextCreate (nil,
                                                  width,
                                                  height,
                                                  kBitsPerComponent,        //每个颜色值8bit
                                                  width*kPixelChannelCount, //每一行的像素点占用的字节数，每个像素点的ARGB四个通道各占8个bit
                                                  colorSpace,
                                                  kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(context, CGRectMake(0, 0, width, height), imgRef);
    unsigned char *bitmapData = CGBitmapContextGetData (context);
    
    //这里把BitmapData进行马赛克转换,就是用一个点的颜色填充一个level*level的正方形
    unsigned char pixel[kPixelChannelCount] = {0};
    NSUInteger index,preIndex;
    for (NSUInteger i = 0; i < height - 1 ; i++) {
        for (NSUInteger j = 0; j < width - 1; j++) {
            index = i * width + j;
            if (i % level == 0) {
                if (j % level == 0) {
                    memcpy(pixel, bitmapData + kPixelChannelCount*index, kPixelChannelCount);
                }else{
                    memcpy(bitmapData + kPixelChannelCount*index, pixel, kPixelChannelCount);
                }
            } else {
                preIndex = (i-1)*width +j;
                memcpy(bitmapData + kPixelChannelCount*index, bitmapData + kPixelChannelCount*preIndex, kPixelChannelCount);
            }
        }
    }
    
    NSInteger dataLength = width*height* kPixelChannelCount;
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, bitmapData, dataLength, NULL);
    //创建要输出的图像
    CGImageRef mosaicImageRef = CGImageCreate(width, height,
                                              kBitsPerComponent,
                                              kBitsPerPixel,
                                              width*kPixelChannelCount ,
                                              colorSpace,
                                              kCGImageAlphaPremultipliedLast,
                                              provider,
                                              NULL, NO,
                                              kCGRenderingIntentDefault);
    CGContextRef outputContext = CGBitmapContextCreate(nil,
                                                       width,
                                                       height,
                                                       kBitsPerComponent,
                                                       width*kPixelChannelCount,
                                                       colorSpace,
                                                       kCGImageAlphaPremultipliedLast);
    CGContextDrawImage(outputContext, CGRectMake(0.0f, 0.0f, width, height), mosaicImageRef);
    CGImageRef resultImageRef = CGBitmapContextCreateImage(outputContext);
    UIImage *resultImage = nil;
    if([UIImage respondsToSelector:@selector(imageWithCGImage:scale:orientation:)]) {
        float scale = [[UIScreen mainScreen] scale];
        resultImage = [UIImage imageWithCGImage:resultImageRef scale:scale orientation:UIImageOrientationUp];
    } else {
        resultImage = [UIImage imageWithCGImage:resultImageRef];
    }
    //释放
    if(resultImageRef){
        CFRelease(resultImageRef);
    }
    if(mosaicImageRef){
        CFRelease(mosaicImageRef);
    }
    if(colorSpace){
        CGColorSpaceRelease(colorSpace);
    }
    if(provider){
        CGDataProviderRelease(provider);
    }
    if(context){
        CGContextRelease(context);
    }
    if(outputContext){
        CGContextRelease(outputContext);
    }
    return resultImage;
}


/**截图*/
- (UIImage *)snapImage
{
    UIGraphicsBeginImageContextWithOptions(self.jigsawView.bounds.size, YES, 0);
    [self.jigsawView drawViewHierarchyInRect:self.jigsawView.bounds afterScreenUpdates:YES];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/**添加文字水印*/
- (void)addText:(NSString *)text
{
    self.canScrollImage = NO;
    UILabel *label = [[UILabel alloc] init];
    label.userInteractionEnabled = YES;
    [label addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panLabel:)]];
    label.text = text;
    label.textColor = kRGBColor(211,211,211);
    label.tag = 2;
    [self.jigsawView addSubview:label];
    
    [label sizeToFit];
    label.center = self.jigsawView.center;
}


//拖动label
- (void)panLabel:(UIPanGestureRecognizer *)pan
{
    UIView *label = pan.view;
    if ([label isKindOfClass: UILabel.class]) {
        
        //获取拖拽手势在self.view 的拖拽姿态
        CGPoint translation = [pan translationInView:self.jigsawView];
        //改变panGestureRecognizer.view的中心点 就是self.imageView的中心点
        pan.view.center = CGPointMake(pan.view.center.x + translation.x, pan.view.center.y + translation.y);
        //重置拖拽手势的姿态
        [pan setTranslation:CGPointZero inView:self.jigsawView];
        
    }
}

/**进入马赛克状态*/
- (void)enterMaskStatus
{
    self.canScrollImage = NO;
    if (self.maskPaintView) {
        [self.maskPaintView removeFromSuperview];
    }
    
    
    //获取原图和马赛克图片
    UIImage *originImage = [self snapImage];
    UIImage *maskImage = [self maskWithImage:originImage blockLevel:20];
    
    //创建遮罩视图
    XMMaskPaintView *maskPaintView = [[XMMaskPaintView alloc] initWithFrame:self.jigsawView.bounds];
    maskPaintView.image = maskImage;
    maskPaintView.surfaceImage = originImage;
    maskPaintView.type = XMMaskPaintViewTypeMask;
    [self.jigsawView addSubview:maskPaintView];
    self.maskPaintView = maskPaintView;
    self.maskPaintView.userInteractionEnabled = YES;
}

- (void)enterEraser
{
    self.canScrollImage = NO;
    self.maskPaintView.userInteractionEnabled = YES;
    self.maskPaintView.type = XMMaskPaintViewTypeEraser;
}

-(void)enterNormal{
    self.maskPaintView.userInteractionEnabled = NO;
    if(self.maskPaintView.path == nil ){
        [self.maskPaintView removeAllSubviews];
        [self.maskPaintView removeFromSuperview];
        self.canScrollImage = YES;
    }
}

/**撤销马赛克*/
- (void)backMask
{
    [self.maskPaintView backPath];
}

/**重绘马赛克*/
- (void)forwardMask
{
    [self.maskPaintView forwardPath];
}

//清除文字水印
-(void)clearAttach{
    for (UIView * view in  self.jigsawView.subviews) {
        if ([view isKindOfClass:[UILabel class]] && view.tag == 2) {
            [view removeFromSuperview];
        }
    }
    
}


-(void)setCanScrollImage:(BOOL)canScrollImage{
    _canScrollImage = canScrollImage;
    
    for (UIView * subView in self.jigsawView.subviews) {
        if ([subView isKindOfClass:[XMAlbumScrollView class]]) {
            XMAlbumScrollView * imageView = (XMAlbumScrollView *)subView;
            imageView.userInteractionEnabled = canScrollImage;
        }
    }
    
}

@end
